<?php

namespace app\backstage\controller;


use app\model\Task as model;
use app\model\FreshAdminUser;
use app\model\FreshAdminAuthGroupAccess;
use app\model\TaskRecord;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use app\util\ReturnCode;
use app\util\Tools;
use think\Db;

class Task extends Base {

    public function index(){
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();
        $where = function($query)use($postData){
            if(isset($postData['status'])){
                $query->where('u.status', intval($postData['status']));
            }
            if(isset($postData['keyword'])&& $postData['keyword']){
                $query->where('u.title',  'like','%'.$postData['keyword'].'%');
            }
            if(isset($postData['type'])&& $postData['type']){
                $query->where('u.type', $postData['type']);
            }
            if(isset($postData['isOpen'])&& $postData['isOpen']){
                $query->where('u.isOpen', $postData['isOpen']);
            }

           /* $platformID = $this->userPlatform();
            if($platformID == 0){
                if(isset($postData['platformID']) && $postData['platformID']){
                    $query->where('u.platformID', $postData['platformID']);
                }
            }else{
                $query->where('u.platformID', $platformID);
            }*/

            if(isset($postData['beginTime']) && $postData['beginTime']){
                $query->where('u.addTime', '>=', strtotime($postData['beginTime']));
            }
            if(isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', '<=', $endTime);
            }
            if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', [ '>=' , strtotime($postData['beginTime'])],['<=', $endTime], 'and');
            }


        };



        $list = model::alias('u')
        ->field('u.*,t.name as typeName,a.username as checkManagerName,p.name as platformName,a1.nickname as addUserName,a1.username addUserAccout')
        ->join('task_type t', 't.id=u.type', 'left')
        ->join('fresh_admin_user a', 'a.id=u.checkManager', 'left')
        ->join('fresh_admin_user a1', 'a1.id=u.addUser', 'left')
        ->join('platform p', 'p.id=u.platformID', 'left')
        ->where($where)
        ->order('sort desc,addTime desc')
        ->limit(( $page - 1 ) * $size , $size)
        ->select();
        if($list){
            $list->append(['statusText', 'isUpText', 'isOpenText', 'timesText']);
        }

        foreach($list as $key => $var){
            $var->data('checkTimeStr', $var['checkTime'] ? date("Y-m-d H:i:s", $var['checkTime']) : '');
        }

        $count =   model::alias('u')
        ->join('task_type t', 't.id=u.type', 'left')
        ->where($where)
        ->count();

        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list
        ]);
    }


    public function opindex(){
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();
        $where = function($query)use($postData){
            if(isset($postData['status'])){
                $query->where('u.status', intval($postData['status']));
            }
            if(isset($postData['keyword'])&& $postData['keyword']){
                $query->where('u.title',  'like','%'.$postData['keyword'].'%');
            }
            if(isset($postData['type'])&& $postData['type']){
                $query->where('u.type', $postData['type']);
            }
            if(isset($postData['isOpen'])&& $postData['isOpen']){
                $query->where('u.isOpen', $postData['isOpen']);
            }
            if(isset($postData['platformID'])&& $postData['platformID']){
                $query->where('u.platformID', $postData['platformID']);
            }
            if(isset($postData['beginTime']) && $postData['beginTime']){
                $query->where('u.addTime', '>=', strtotime($postData['beginTime']));
            }
            if(isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', '<=', $endTime);
            }
            if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', [ '>=' , strtotime($postData['beginTime'])],['<=', $endTime], 'and');
            }
            $userPlatform = $this->userPlatform();
            if($userPlatform){
                $query->where('u.platformID', $userPlatform);
            }

        };



        $list = model::alias('u')
            ->field('u.*,t.name as typeName,a.username as checkManagerName,p.name as platformName,a1.nickname as addUserName,a1.username addUserAccout')
            ->join('task_type t', 't.id=u.type', 'left')
            ->join('fresh_admin_user a', 'a.id=u.checkManager', 'left')
            ->join('fresh_admin_user a1', 'a1.id=u.addUser', 'left')
            ->join('platform p', 'p.id=u.platformID', 'left')
            ->where($where)
            ->order('sort desc,addTime desc')
            ->limit(( $page - 1 ) * $size , $size)
            ->select();
        if($list){
            $list->append(['statusText', 'isUpText', 'isOpenText', 'timesText']);
        }

        foreach($list as $key => $var){
            $var->data('checkTimeStr', $var['checkTime'] ? date("Y-m-d H:i:s", $var['checkTime']) : '');
        }

        $count =   model::alias('u')
            ->join('task_type t', 't.id=u.type', 'left')
            ->where($where)
            ->count();

        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list
        ]);
    }

    public function add(){

        $postData = $this->request->post();
        if(!isset($postData['title']) || empty($postData['title'])){
            return $this->buildFailed(ReturnCode::INVALID, '任务标题为空');
        }
        if(mb_strlen($postData['title']) > 200){
            return $this->buildFailed(ReturnCode::INVALID, '任务标题大于200字符');
        }
        // if(!isset($postData['startYmd']) || empty($postData['startYmd'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '开始日期为空');
        // }
        if(isset($postData['startYmd']) && $postData['startYmd'] && (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$postData['startYmd'], $match) || !strtotime($postData['startYmd']))){
            return $this->buildFailed(ReturnCode::INVALID, '开始日期格式错误');
        }
        // if(!isset($postData['endYmd']) || empty($postData['endYmd'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '开始日期为空');
        // }
        if(isset($postData['endYmd']) && $postData['endYmd'] && (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$postData['endYmd'], $match) || !strtotime($postData['endYmd']))){
            return $this->buildFailed(ReturnCode::INVALID, '结束日期格式错误');
        }
        // if(!isset($postData['dayStart']) || empty($postData['dayStart'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '每天开始时间为空');
        // }
        if( isset($postData['dayStart']) &&  $postData['dayStart'] && (!preg_match('/^\d{2}:\d{2}:\d{2}$/',$postData['dayStart'], $match) || !strtotime('2020-02-02 ' . $postData['dayStart']))){
            return $this->buildFailed(ReturnCode::INVALID, '每天开始时间格式错误');
        }

        // if(!isset($postData['dayEnd']) || empty($postData['dayEnd'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '每天结束时间为空');
        // }
        if(isset($postData['dayEnd']) && $postData['dayEnd'] && (!preg_match('/^\d{2}:\d{2}:\d{2}$/',$postData['dayEnd'], $match) || !strtotime('2020-02-02 ' . $postData['dayStart']))){
            return $this->buildFailed(ReturnCode::INVALID, '每天结束时间格式错误');
        }

        if(isset($postData['dayEnd']) && isset($postData['dayStart']) && $postData['dayEnd'] && $postData['dayStart'] &&$postData['dayEnd'] < $postData['dayStart']){
            return $this->buildFailed(ReturnCode::INVALID, '每天结束时间不能小于每日开始时间');
        }
        if(!isset($postData['times']) || empty($postData['times'])){
            return $this->buildFailed(ReturnCode::INVALID, '请选择重复次数');
        }
        if(!isset($postData['type']) || empty($postData['type'])){
            return $this->buildFailed(ReturnCode::INVALID, '请选择任务类型');
        }
        if(!isset($postData['num']) || empty($postData['num'])){
            return $this->buildFailed(ReturnCode::INVALID, '请填写剩余次数');
        }
        $userPlatform = $this->userPlatform();
        if(empty($userPlatform) && (!isset($postData['platformID']) || empty($postData['platformID']))){
            return $this->buildFailed(ReturnCode::INVALID, '请选择平台');
        }
        $platformID = $userPlatform ? : $postData['platformID'];
        $data = [
            'title' => $postData['title'],
            'startYmd' => isset($postData['startYmd']) && $postData['startYmd'] ? $postData['startYmd'] : '',
            'endYmd' => isset($postData['endYmd']) && $postData['endYmd'] ? $postData['endYmd'] : '',
            'dayStart' => isset($postData['dayStart']) && $postData['dayStart'] ? $postData['dayStart'] : '',
            'dayEnd' => isset($postData['dayEnd']) && $postData['dayEnd'] ? $postData['dayEnd'] : '',
            'times' => $postData['times'],
            'type' => $postData['type'],
            'logo' => isset($postData['logo']) ? $postData['logo'] : '',
            'video' => isset($postData['video']) ? $postData['video'] : '',
            'content' => isset($postData['content']) ? $postData['content'] : '',
            'standardImg' => isset($postData['standardImg']) ? $postData['standardImg'] : '',
            'isOpen' => isset($postData['isOpen']) && in_array($postData['isOpen'], [1, 2]) ? $postData['isOpen'] : 1,
            'rewardName' => isset($postData['rewardName']) ? $postData['rewardName'] : '',
            'rewardMoney' => isset($postData['rewardMoney']) ? Tools::bcCalculate($postData['rewardMoney'], 100, '*', 0) : 0,
            'rewardNum' => isset($postData['rewardNum']) ? $postData['rewardNum'] : 0,
            'platformID' => $platformID,
            'sort' => isset($postData['sort']) ? $postData['sort'] : 0,
            'num' => isset($postData['num']) ? $postData['num'] : 0,
            'yuguMoney' => isset($postData['yuguMoney']) ? $postData['yuguMoney'] : 0,
            'label' => isset($postData['label']) ? $postData['label'] : '',
            'isUp' => isset($postData['isUp']) && in_array($postData['isUp'], [1, 2]) ? $postData['isUp'] : 2,
            'addUser' => $this->userInfo['id']
        ];


        $res = model::create($data);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }

    }


    public function edit(){
        $postData = $this->request->post();
        if(!isset($postData['taskID']) || empty($postData['taskID'])){
            return $this->buildFailed(ReturnCode::INVALID, 'taskID为空');
        }
        if(!isset($postData['title']) || empty($postData['title'])){
            return $this->buildFailed(ReturnCode::INVALID, '任务标题为空');
        }
        if(mb_strlen($postData['title']) > 200){
            return $this->buildFailed(ReturnCode::INVALID, '任务标题大于200字符');
        }
        // if(!isset($postData['startYmd']) || empty($postData['startYmd'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '开始日期为空');
        // }
        if(isset($postData['startYmd']) && $postData['startYmd'] && (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$postData['startYmd'], $match) || !strtotime($postData['startYmd']))){
            return $this->buildFailed(ReturnCode::INVALID, '开始日期格式错误');
        }
        // if(!isset($postData['endYmd']) || empty($postData['endYmd'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '开始日期为空');
        // }
        if(isset($postData['endYmd']) && $postData['endYmd'] && (!preg_match('/^\d{4}-\d{2}-\d{2}$/',$postData['endYmd'], $match) || !strtotime($postData['endYmd']))){
            return $this->buildFailed(ReturnCode::INVALID, '结束日期格式错误');
        }
        // if(!isset($postData['dayStart']) || empty($postData['dayStart'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '每天开始时间为空');
        // }
        if( isset($postData['dayStart']) &&  $postData['dayStart'] && (!preg_match('/^\d{2}:\d{2}:\d{2}$/',$postData['dayStart'], $match) || !strtotime('2020-02-02 ' . $postData['dayStart']))){
            return $this->buildFailed(ReturnCode::INVALID, '每天开始时间格式错误');
        }

        // if(!isset($postData['dayEnd']) || empty($postData['dayEnd'])){
        //     return $this->buildFailed(ReturnCode::INVALID, '每天结束时间为空');
        // }
        if(isset($postData['dayEnd']) && $postData['dayEnd'] && (!preg_match('/^\d{2}:\d{2}:\d{2}$/',$postData['dayEnd'], $match) || !strtotime('2020-02-02 ' . $postData['dayStart']))){
            return $this->buildFailed(ReturnCode::INVALID, '每天结束时间格式错误');
        }

        if(isset($postData['dayEnd']) && isset($postData['dayStart']) && $postData['dayEnd'] && $postData['dayStart'] && $postData['dayEnd'] < $postData['dayStart']){
            return $this->buildFailed(ReturnCode::INVALID, '每天结束时间不能小于每日开始时间');
        }
        if(!isset($postData['times']) || empty($postData['times'])){
            return $this->buildFailed(ReturnCode::INVALID, '请选择重复次数');
        }
        if(!isset($postData['type']) || empty($postData['type'])){
            return $this->buildFailed(ReturnCode::INVALID, '请选择任务类型');
        }

        $task = model::get($postData['taskID']);
        if(empty($task)){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '任务不存在');
        }
        $data = [
            'title' => $postData['title'],
            'startYmd' => isset($postData['startYmd']) && $postData['startYmd'] ? $postData['startYmd'] : '',
            'endYmd' => isset($postData['endYmd']) && $postData['endYmd'] ? $postData['endYmd'] : '',
            'dayStart' => isset($postData['dayStart']) && $postData['dayStart'] ? $postData['dayStart'] : '',
            'dayEnd' => isset($postData['dayEnd']) && $postData['dayEnd'] ? $postData['dayEnd'] : '',
            'times' => $postData['times'],
            'type' => $postData['type'],
            'logo' => isset($postData['logo']) ? $postData['logo'] : '',
            'video' => isset($postData['video']) ? $postData['video'] : '',
            'content' => isset($postData['content']) ? $postData['content'] : '',
            'standardImg' => isset($postData['standardImg']) ? $postData['standardImg'] : '',
            'isOpen' => isset($postData['isOpen'])  && in_array($postData['isOpen'], [1, 2]) ? $postData['isOpen'] : 1,
            'rewardName' => isset($postData['rewardName']) ? $postData['rewardName'] : '',
            'rewardMoney' => isset($postData['rewardMoney']) ? Tools::bcCalculate($postData['rewardMoney'], 100, '*', 0) : 0,
            'rewardNum' => isset($postData['rewardNum']) ? $postData['rewardNum'] : 0,
            'num' => isset($postData['num']) ? $postData['num'] : $task['num'],
            'yuguMoney' => isset($postData['yuguMoney']) ? $postData['yuguMoney'] : $task['yuguMoney'],
            'sort' => isset($postData['sort']) ? $postData['sort'] : 0,
            'label' => isset($postData['label']) ? $postData['label'] : '',
            'isUp' => isset($postData['isUp']) && in_array($postData['isUp'], [1, 2]) ? $postData['isUp'] : 2,
            'status' => -1,
        ];



        $userPlatform = $this->userPlatform();
        if($userPlatform &&  $task->platformID != $userPlatform){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '不能编辑其他平台任务');
        }
        $task->data($data);
        if ($task->isUpdate(true)->save() === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }

    }


    public function listDownload(){
        $postData = $this->request->get();
        if(!isset($postData['acces_token']) || $postData['acces_token'] != 's4f_nds5hiddfsmb9'){
            die('forbidden');
        }
        $where = function($query)use($postData){
            if(isset($postData['status'])){
                $query->where('u.status', intval($postData['status']));
            }
            if(isset($postData['keyword'])&& $postData['keyword']){
                $query->where('u.title',  'like','%'.$postData['keyword'].'%');
            }
            if(isset($postData['type'])&& $postData['type']){
                $query->where('u.type', $postData['type']);
            }
            if(isset($postData['isOpen'])&& $postData['isOpen']){
                $query->where('u.isOpen', $postData['isOpen']);
            }
            if(isset($postData['addUser'])&& $postData['addUser']){
                $query->where('u.addUser', $postData['addUser']);
            }
            if(isset($postData['beginTime']) && $postData['beginTime']){
                $query->where('u.addTime', '>=', strtotime($postData['beginTime']));
            }
            if(isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', '<=', $endTime);
            }
            if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('u.addTime', [ '>=' , strtotime($postData['beginTime'])],['<=', $endTime], 'and');
            }

            $platformID = $this->userPlatform();
            if($platformID == 0){
                if(isset($postData['platformID']) && $postData['platformID']){
                    $query->where('u.platformID', $postData['platformID']);
                }
            }else{
                $query->where('u.platformID', $platformID);
            }
        };



        $list = model::alias('u')
        ->field('u.*,t.name as typeName,a.username as checkManagerName,p.name as platformName,a1.nickname as addUserName')
        ->join('task_type t', 't.id=u.type', 'left')
        ->join('fresh_admin_user a', 'a.id=u.checkManager', 'left')
        ->join('fresh_admin_user a1', 'a1.id=u.addUser', 'left')
        ->join('platform p', 'p.id=u.platformID', 'left')
        ->where($where)
        ->order('sort desc,addTime desc')
        ->select();
        if($list){
            $list->append(['statusText', 'isUpText', 'isOpenText', 'timesText']);
        }

        foreach($list as $key => $var){
            $var->data('checkTimeStr', $var['checkTime'] ? date("Y-m-d H:i:s", $var['checkTime']) : '');
        }

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();

        //表头
        //设置单元格内容
        $worksheet->setCellValueByColumnAndRow(1, 1, '任务ID');
        $worksheet->setCellValueByColumnAndRow(2, 1, '任务标题');
        $worksheet->setCellValueByColumnAndRow(3, 1, '任务开始时间');
        $worksheet->setCellValueByColumnAndRow(4, 1, '任务结束时间');
        $worksheet->setCellValueByColumnAndRow(5, 1, '每天的开始时间');
        $worksheet->setCellValueByColumnAndRow(6, 1, '每天的结束时间');
        $worksheet->setCellValueByColumnAndRow(7, 1, '重复次数');
        $worksheet->setCellValueByColumnAndRow(8, 1, '任务类型');
        $worksheet->setCellValueByColumnAndRow(9, 1, '是否开放');
        $worksheet->setCellValueByColumnAndRow(10, 1, '悬赏名称');
        $worksheet->setCellValueByColumnAndRow(11, 1, '悬赏金额');
        $worksheet->setCellValueByColumnAndRow(12, 1, '悬赏人数');
        $worksheet->setCellValueByColumnAndRow(13, 1, '审核人员');
        $worksheet->setCellValueByColumnAndRow(14, 1, '审核时间');
        $worksheet->setCellValueByColumnAndRow(15, 1, '状态');
        $worksheet->setCellValueByColumnAndRow(16, 1, '是否上架');
        $worksheet->setCellValueByColumnAndRow(17, 1, '添加时间');
        $worksheet->setCellValueByColumnAndRow(18, 1, '所属平台');
        $worksheet->setCellValueByColumnAndRow(19, 1, '标签');
        $worksheet->setCellValueByColumnAndRow(20, 1, '添加人');
        $worksheet->setCellValueByColumnAndRow(21, 1, '添加时间');
        $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);
        $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(15);
        $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(12);
        $spreadsheet->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('I')->setWidth(12);
        $spreadsheet->getActiveSheet()->getColumnDimension('J')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('O')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('Q')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('R')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('T')->setWidth(20);
        $spreadsheet->getActiveSheet()->getColumnDimension('U')->setWidth(25);
        $styleArray = [
            'font' => [
                'bold' => true
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $worksheet->getStyle('A1:U1')->applyFromArray($styleArray)->getFont()->setSize(12); //头部样式设置
        $len = count($list);
        $j = 0;
        for ($i = 0; $i < $len; $i++) {
            $j = $i + 2; //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $list[$i]['taskID']);
            $worksheet->setCellValueByColumnAndRow(2, $j, $list[$i]['title']);
            $worksheet->setCellValueByColumnAndRow(3, $j, $list[$i]['startYmd']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $list[$i]['endYmd']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $list[$i]['dayStart']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $list[$i]['dayEnd']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $list[$i]['timesText']);
            $worksheet->setCellValueByColumnAndRow(8, $j, $list[$i]['typeName']);
            $worksheet->setCellValueByColumnAndRow(9, $j, $list[$i]['isOpenText']);
            $worksheet->setCellValueByColumnAndRow(10, $j, $list[$i]['rewardName']);
            $worksheet->setCellValueByColumnAndRow(11, $j, $list[$i]['rewardMoney']);
            $worksheet->setCellValueByColumnAndRow(12, $j, $list[$i]['rewardNum']);
            $worksheet->setCellValueByColumnAndRow(13, $j, $list[$i]['checkManagerName']);
            $worksheet->setCellValueByColumnAndRow(14, $j, $list[$i]['checkTimeStr']);
            $worksheet->setCellValueByColumnAndRow(15, $j, $list[$i]['statusText']);
            $worksheet->setCellValueByColumnAndRow(16, $j, $list[$i]['isUpText']);
            $worksheet->setCellValueByColumnAndRow(17, $j, $list[$i]['addTime']);
            $worksheet->setCellValueByColumnAndRow(18, $j, $list[$i]['platformName']);
            $worksheet->setCellValueByColumnAndRow(19, $j, $list[$i]['label']);
            $worksheet->setCellValueByColumnAndRow(20, $j, $list[$i]['addUserName']);
            $worksheet->setCellValueByColumnAndRow(21, $j, $list[$i]['addTime']);
        }
        if (!empty($postData['beginTime']) && $postData['beginTime'] && !empty($postData['endTime']) && $postData['endTime']) {
            $date = $postData['beginTime'] . " 至 " . $postData['endTime'] . ' 23:59:59';
            $worksheet->setCellValueByColumnAndRow(2, $j + 1, $date);
        }

        $styleArrayBody = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => '666666'],
                ],
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $total_rows = $len + 2;
        //添加所有边框/居中
        $worksheet->getStyle('A1:U' . $total_rows)->applyFromArray($styleArrayBody);

        $filename = '任务列表.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

      }


    public function setStatus(){
        $postData = $this->request->post();
        if(!isset($postData['taskID']) || empty($postData['taskID'])){
            return $this->buildFailed(ReturnCode::INVALID, 'taskID为空');
        }
        if(!isset($postData['status']) || empty($postData['status'])){
            return $this->buildFailed(ReturnCode::INVALID, '状态值为空');
        }
        if($postData['status'] < 1 || $postData['status'] > 9){
            return $this->buildFailed(ReturnCode::INVALID, '无效状态值');
        }
        $task = model::get($postData['taskID']);
        if(empty($task)){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '任务不存在');
        }
        $userPlatform = $this->userPlatform();
        if($userPlatform &&  $task->platformID != $userPlatform){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '不能编辑其他平台任务');
        }
       $res = model::where('taskID', $postData['taskID'])->update(['status' => $postData['status'], 'checkManager' => $this->userInfo['id'], 'checkTime'=>time(), 'updateTime' =>time()]);
       if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            if($postData['status'] == 9){
                TaskRecord::where('taskID', $postData['taskID'])->update(['status' => 2, 'remark' => '任务取消取消分配', 'updateTime' => time()]);
            }
            return $this->buildSuccess([]);
        }
    }

    public function setIsUp(){
        $postData = $this->request->post();
        if(!isset($postData['taskID']) || empty($postData['taskID'])){
            return $this->buildFailed(ReturnCode::INVALID, 'taskID为空');
        }
        if(!isset($postData['isUp']) || empty($postData['isUp'])){
            return $this->buildFailed(ReturnCode::INVALID, '上下架状态值为空');
        }
        $task = model::get($postData['taskID']);
        if(empty($task)){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '任务不存在');
        }
        $userPlatform = $this->userPlatform();
        if($userPlatform &&  $task->platformID != $userPlatform){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '不能编辑其他平台任务');
        }
        $res = model::where('taskID', $postData['taskID'])->update(['isUp' => $postData['isUp'], 'updateTime' =>time()]);
        if ($res === false) {
             return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
         } else {
            if($postData['isUp'] == 2){
                TaskRecord::where('taskID', $postData['taskID'])->update(['status' => 2, 'remark' => '任务下架取消分配', 'updateTime' => time()]);
            }
             return $this->buildSuccess([]);
         }
    }

    public function operationList(){
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();
        $where = function($query)use($postData){
            if(isset($postData['keyword'])&& $postData['keyword']){
                $query->where('u.username|u.nickname',  'like','%'.$postData['keyword'].'%');
            }
            if(isset($postData['taskID'])&& $postData['taskID']){
                $opList = TaskRecord::field('opMid')->where(['taskID' => $postData['taskID'], 'status' => 1])->select()->toArray();
                if($opList){
                    $userIds = array_column($opList, 'opMid');
                    $query->where('u.id',  'not in', $userIds);
                }
            }
        };
        $groupWhere = ['g.isOp' => 1];
        $platformID = $this->userPlatform();
        if($platformID){
            $groupWhere['g.platformID'] = $platformID;
        }else{
            if(isset($postData['platformID'])&& $postData['platformID']){
                $groupWhere['g.platformID'] = $postData['platformID'];
            }
        }

        $list = FreshAdminUser::alias('u')
        ->field('u.id,u.username,u.nickname,count(r.taskRecordID) as countNum,p.name as platformName')
        ->join('task_record r', 'r.opMid=u.id', 'left')
        ->join('fresh_admin_auth_group_access c', 'c.uid=u.id', 'left')
        ->join('fresh_admin_auth_group g', 'c.groupId=g.id', 'left')
        ->join('platform p', 'p.id=g.platformID', 'left')
        ->where($where)
        ->where($groupWhere)
        ->group('r.opMid')
        ->limit(( $page - 1 ) * $size , $size)
        ->select();

        $count = FreshAdminUser::alias('u')
        ->join('task_record r', 'r.opMid=u.id', 'left')
        ->join('fresh_admin_auth_group_access c', 'c.uid=u.id', 'left')
        ->join('fresh_admin_auth_group g', 'c.groupId=g.id', 'left')
        ->join('platform p', 'p.id=g.platformID', 'left')
        ->where($where)
        ->where($groupWhere)
        ->group('r.opMid')
        ->count();

        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list
        ]);
    }


    public function addRecord(){
        $postData = $this->request->post();
        if(!isset($postData['taskID']) || empty($postData['taskID'])){
            return $this->buildFailed(ReturnCode::INVALID, 'taskID为空');
        }
        if(!isset($postData['opMid']) || empty($postData['opMid'])){
            return $this->buildFailed(ReturnCode::INVALID, 'opMid为空');
        }
        $res = TaskRecord::where(['taskID' => $postData['taskID'], 'opMid' => $postData['opMid']])->find();
        if($res){
            return $this->buildFailed(ReturnCode::INVALID, '任务重复分配');
        }
        $task = model::get($postData['taskID']);
        $user = FreshAdminAuthGroupAccess::alias('a')
        ->field('a.uid,a.groupId,g.platformID,g.isOp')
        ->join('fresh_admin_auth_group g', 'a.groupId=g.id', 'left')
        ->where('a.uid', $postData['opMid'])
        ->find();
        if($user['isOp'] != 1){
            return $this->buildFailed(ReturnCode::INVALID, '用户非操作员');
        }
        $platformID = $this->userPlatform();
        if($platformID && $task->platformID != $platformID){
            return $this->buildFailed(ReturnCode::INVALID, '不能跨平台分配任务');
        }
        if($user['platformID'] != $task->platformID){
            return $this->buildFailed(ReturnCode::INVALID, '操作员平台与任务所属平台不匹配');
        }
        $data = [
            'taskID' => $postData['taskID'],
            'opMid' => $postData['opMid'],
            'status' => 1
        ];
        if(TaskRecord::create($data)){
            return $this->buildSuccess([]);
        }
        return $this->buildFailed(ReturnCode::INVALID, '分配失败');
    }


    public function delRecord(){
        $postData = $this->request->post();
        if(!isset($postData['taskRecordID']) || empty($postData['taskRecordID'])){
            return $this->buildFailed(ReturnCode::INVALID, 'taskRecordID为空');
        }
        if(false === TaskRecord::where(['taskRecordID' => $postData['taskRecordID']])->update(['status' => 2])){
            return $this->buildFailed(ReturnCode::INVALID, '取消分配失败');
        }
        return $this->buildSuccess([]);
    }

    public function recordList(){
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();
        $where = function($query)use($postData){
            if(isset($postData['keyword'])&& $postData['keyword']){
                $query->where('u.username|u.nickname|t.title',  'like','%'.$postData['keyword'].'%');
            }
            if(isset($postData['status'])){
                $query->where('u.status', intval($postData['status']));
            }else{
                $query->where('u.status', 1);
            }
            if(isset($postData['taskID'])){
                $query->where('r.taskID', intval($postData['taskID']));
            }
            if(isset($postData['platformID'])){
                $query->where('t.platformID', intval($postData['platformID']));
            }
            if(isset($postData['opMid'])){
                $query->where('r.opMid', intval($postData['opMid']));
            }
            if(isset($postData['beginTime']) && $postData['beginTime']){
                $query->where('r.addTime', '>=', strtotime($postData['beginTime']));
            }
            if(isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('r.addTime', '<=', $endTime);
            }
            if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('r.addTime', [ '>=' , strtotime($postData['beginTime'])],['<=', $endTime], 'and');
            }
        };
        $platformID = $this->userPlatform();
        $groupWhere = [];
        if($platformID){
            $groupWhere['t.platformID'] = $platformID;
        }
        $list = TaskRecord::alias('r')
        ->field('u.username,u.nickname,t.title,t.logo,t.startYmd,t.endYmd,t.dayStart,t.dayEnd,t.times,t.type,t.video,t.content,tt.name as typeName,r.taskID,r.addTime,r.taskRecordID,p.name as platformName,r.status')
        ->join('fresh_admin_user u', 'u.id=r.opMid', 'left')
        ->join('task t', 't.taskID=r.taskID', 'left')
        ->join('task_type tt', 'tt.id=t.type', 'left')
        ->join('platform p', 'p.id=t.platformID', 'left')
        ->where($where)
        ->where($groupWhere)
        ->limit(( $page - 1 ) * $size , $size)
        ->select();

        if($list){
            $list->append(['statusText']);
        }
        $timeTypes = ['1' => '每天一次', '2' => '每周一次', '3' => '每月一次', '4' => '每年一次', 5 => '只能一次'];
        foreach($list as $key => $var){
            $var->data('timesText', isset($timeTypes[$var['times']]) ? $timeTypes[$var['times']] : '未知');
        }

        $count = TaskRecord::alias('r')
        ->join('fresh_admin_user u', 'u.id=r.opMid', 'left')
        ->join('task t', 't.taskID=r.taskID', 'left')
        ->join('platform p', 'p.id=t.platformID', 'left')
        ->where($where)
        ->where($groupWhere)
        ->count();

        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list
        ]);
    }

    public function operRecordList(){
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();
        $where = function($query)use($postData){
            if(isset($postData['keyword'])&& $postData['keyword']){
                $query->where('t.title',  'like','%'.$postData['keyword'].'%');
            }
            if(isset($postData['status'])){
                $query->where('u.status', intval($postData['status']));
            }else{
                $query->where('u.status', 1);
            }
            if(isset($postData['taskID'])){
                $query->where('r.taskID', intval($postData['taskID']));
            }
            if(isset($postData['beginTime']) && $postData['beginTime']){
                $query->where('r.addTime', '>=', strtotime($postData['beginTime']));
            }
            if(isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('r.addTime', '<=', $endTime);
            }
            if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
                $endTime = strtotime($postData['endTime']) + 3600*24 -1;
                $query->where('r.addTime', [ '>=' , strtotime($postData['beginTime'])],['<=', $endTime], 'and');
            }
            $query->where('r.opMid', $this->userInfo['id']);
        };
        $list = TaskRecord::alias('r')
        ->field('u.username,u.nickname,t.title,t.logo,t.startYmd,t.endYmd,t.dayStart,t.dayEnd,t.times,t.type,t.video,t.content,tt.name as typeName,r.taskID,r.addTime,r.taskRecordID,p.name as platformName,r.status')
        ->join('fresh_admin_user u', 'u.id=r.opMid', 'left')
        ->join('task t', 't.taskID=r.taskID', 'left')
        ->join('task_type tt', 'tt.id=t.type', 'left')
        ->join('platform p', 'p.id=t.platformID', 'left')
        ->where($where)
        ->limit(( $page - 1 ) * $size , $size)
        ->select();

        if($list){
            $list->append(['statusText']);
        }
        $timeTypes = ['1' => '每天一次', '2' => '每周一次', '3' => '每月一次', '4' => '每年一次', 5 => '只能一次'];
        foreach($list as $key => $var){
            $var->data('timesText', isset($timeTypes[$var['times']]) ? $timeTypes[$var['times']] : '未知');
        }

        $count = TaskRecord::alias('r')
        ->join('fresh_admin_user u', 'u.id=r.opMid', 'left')
        ->join('task t', 't.taskID=r.taskID', 'left')
        ->join('platform p', 'p.id=t.platformID', 'left')
        ->where($where)
        ->count();

        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list
        ]);
    }

}

?>
